package x.trident.core.sequence.starter.autoconfiguration;

import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.data.redis.core.script.RedisScript;
import x.trident.core.sequence.starter.impl.SequenceClient;

import java.util.concurrent.ScheduledExecutorService;

/**
 * starter自动加载（读取lua脚本）
 *
 * @author 林选伟
 * @date 2023-06-01
 */
@Configuration
@Slf4j
public class SequenceAutoConfiguration implements EnvironmentAware, DisposableBean {
    private ScheduledExecutorService scheduledExecutorService;

    @Bean
    @ConditionalOnMissingBean(name = "loadSeqenceLuaScript")
    public RedisScript<Long> getNormalSeqNumScript() throws Exception {
        return AutoConfigurationUtils.loadSeqenceLuaScript();
    }

    @Bean
    @ConditionalOnMissingBean(name = "sequenceClient")
    public SequenceClient sequenceClient(@Qualifier("getNormalSeqNumScript") RedisScript<Long> normalSeqNumScript) {
        SequenceClient sequenceClient = new SequenceClient();
        sequenceClient.setNormalSeqNumScript(normalSeqNumScript);
        return sequenceClient;
    }


    @Override
    public void setEnvironment(@NonNull Environment environment) {
    }

    @Override
    public void destroy() {
        try {
            if (scheduledExecutorService != null) {
                scheduledExecutorService.shutdown();
            }
        } catch (Exception e) {
            // nothing
        }
    }
}
